﻿#pragma once 

#include "ui_pwdDlg.h"
#include "ui_reNamDlg.h"
#include "ui_checkSetDlg.h"
#include "ui_bitSetDlg.h"
#include "ui_snapShotDlg.h"
#include "ui_hexViewDlg.h"
#include "ui_softInfoDlg.h"
#include "ui_extraParmsDlg.h"
#include "ui_evfsCfgDlg.h"
#include "ui_crossWireDlg.h"
#include "tipDlgs.h"
#include "ConfigFile.h"
#include "QMessageBox"
#include <QRegExp>
#include <QDebug>
#include <future>
#include "EagleDeviceMgr.h"
#include "statisticsanalyze.h"
#include "DecoderPlugin.h"
#include "PluginMgr.h"
#include <QImage>
#include "QAbstractItemModel"
#include "common.h"
#include "QFileDialog"
#include "QBrush"
#include "QDebug"
#include <QDebug>
#include <QFrame>
#include "qdisplaywidget.h"
#include "qevent.h"
#include <QRegExp>

pwdDlg::pwdDlg(QWidget* parent)
:QDialog(parent), ui(new Ui::pwdDlg)
{
	ui->setupUi(this);
	setFixedSize(300, 120);
}

void pwdDlg::accept()
{
	if (ui->lineEdit->text() == EagleConfigFile::getInstance()->password)
	{
		return QDialog::accept();
	}
	else
	{
		QMessageBox::warning(this, tr("密码验证错误"), tr("密码错误，请重新输入!!"));
		ui->lineEdit->setText("");
	}
}

//////////////////////////////////////////////////////////////////////////
//  [12/8/2016 ejitec]

renameDlg::renameDlg(QWidget* parent)
:QDialog(parent), ui(new Ui::reNamDlg)
{
	ui->setupUi(this);
	setFixedSize(300, 120);
}

void renameDlg::accept()
{
	QString strText = ui->lineEdit->text();
	if (strText.contains(QRegExp("^\\w{1,32}$", Qt::CaseInsensitive)))
	{
		return QDialog::accept();
	}
	else
	{
		QMessageBox::warning(this, GetMessageBoxTitle(), GetLogFormat(EagleLog_M_Invalid_Task_Name_Alarm));
		//QMessageBox::warning(this, tr("重命名非法输入"), tr("重命名名称"));
		ui->lineEdit->setText("");
	}
}

QString renameDlg::getNewName()
{
	return ui->lineEdit->text();
}


//////////////////////////////////////////////////////////////////////////
//  [12/8/2016 ejitec]
bitSetDlg::bitSetDlg(QWidget* parent, bool &decoder_changed, int nColorDepth, QString& strDecord, QString& strFormat, bool bDecordSel)
:QDialog(parent), m_bChange(decoder_changed), m_nColorDepth(nColorDepth)
, m_strDecordNam(strDecord), m_strFormatNam(strFormat), m_DecodeSel(bDecordSel)
, ui(new Ui::dlgBitSet)
{
	ui->setupUi(this);

	if (bDecordSel)
	{
		showBitWidthOnly();
		std::map<wstring, DecoderPlugin*> &decoders = DecoderPluginMgr::getInstance()->getDecoders();
		for (std::map<wstring, DecoderPlugin*>::iterator it = decoders.begin(); it != decoders.end(); it++)
		{
			ui->cmb_dec->addItem(QString::fromStdWString(it->first));
		}

		int index = ui->cmb_dec->findText(m_strDecordNam, Qt::MatchExactly);
		if (index != -1)
			ui->cmb_dec->setCurrentIndex(index);
		else
			ui->cmb_dec->setCurrentIndex(0);

		connect(ui->cmb_dec, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
			this, [=](int n)
		{
			
		});
	}
	else
	{
		showFormatOnly();

		std::map<wstring, DecoderPlugin*> &read_formats = DecoderPluginMgr::getInstance()->getReadFormats();
		for (auto it = read_formats.begin(); it != read_formats.end(); it++) {
			ui->cmb_outFmt->addItem(QString::fromStdWString(it->first));
		}
		int index = ui->cmb_outFmt->findText(m_strFormatNam, Qt::MatchExactly);
		if (index != -1)
			ui->cmb_outFmt->setCurrentIndex(index);
		else
			ui->cmb_outFmt->setCurrentIndex(0);
	}
	
}

void bitSetDlg::accept()
{
	m_bChange = true;
	QDisPlayWidget* pThis = (QDisPlayWidget*)parent();
	int _device_id = pThis->DevID();
	int _ccd_serial = pThis->CCDID();

	if (m_DecodeSel)
	{
		m_strDecordNam = ui->cmb_dec->currentText();
		EagleConfigFile::getInstance()->SetDeviceCameraDecoderName(_device_id, _ccd_serial, m_strDecordNam);
	}
	else
	{
		m_strFormatNam = ui->cmb_outFmt->currentText();
	}

	return QDialog::accept();
}

void bitSetDlg::showBitWidthOnly()
{
	ui->groupBox_format->hide();
	ui->groupBox_bitWidth->show();
	setFixedHeight(this->height() * 2 / 3);
}

void bitSetDlg::showFormatOnly()
{
	ui->groupBox_format->show();
	ui->groupBox_bitWidth->hide();
	setFixedHeight(this->height() * 1 / 2);
}

//////////////////////////////////////////////////////////////////////////
// 自检时 选择数据源种类  [12/8/2016 ejitec]
void checkRecordDlg::accept()
{
	std::vector<int> device_list;
	CEagleDeviceMgr::GetInstance()->GetCheckedDeviceList(device_list);

	if (device_list.empty())
	{
		return;
	}

	int nSel = getSelCheckType();
	std::vector<std::future<int>> checker;

	for (auto device_it = device_list.begin(); device_it != device_list.end(); device_it++)
	{
		checker.push_back(std::async(std::launch::async,[=]()
		{
			int device_id = *device_it;
			int task_type = nSel;
			int ret = -1;
			int mode = CEagleDeviceMgr::GetInstance()->GetSdiMode(device_id);
			DISK_MOUNT_TYPE type = (DISK_MOUNT_TYPE)EagleConfigFile::getInstance()->disk_mount_type.toLong();
			std::vector<eagle_capture_config> ccdlist = GetCcdList(device_id);
			for (auto it = ccdlist.begin(); it != ccdlist.end(); it++)
			{
				char shrink_level = 0;
				ret = EagleControl_GetCameraRealtimeShrinkLevel(device_id, it->camera_no, &shrink_level);
				EagleControl_SetCameraRealtimeShrinkLevel(device_id, it->camera_no, shrink_level);
			}
			EagleData_RemoveFileSystem(device_id, type);
			int self_check_type = DATA_SOURCE_CHECK_LINE;
			switch (task_type)
			{
			case 0: self_check_type = DATA_SOURCE_CHECK_LINE; break;
			case 1: self_check_type = DATA_SOURCE_CHECK_COLUMN; break;
			case 2: self_check_type = DATA_SOURCE_CHECK_DIAGONAL; break;
			case 3: self_check_type = DATA_SOURCE_CHECK_MOVING_LINE; break;
			case 4: self_check_type = DATA_SOURCE_CHECK_MOVING_COLUMN; break;
			case 5: self_check_type = DATA_SOURCE_CHECK_MOVING_DIAGONAL; break;
			default:
				break;
			}
			ret = EagleControl_StartTask(device_id, L"chk", self_check_type, mode);
			ControlApiLogger(ret, EagleLog_C_Start_Task, QString("chk"));
			if (ret == 0)
			{
				ret = EagleControl_StartRecord(device_id, 0, 0, 0);
				ControlApiLogger(ret, EagleLog_C_Start_Record, 0);
			}

			return ret;
		}));
	}

	qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
	
	while (true)
	{
		bool all_check_thread_finished = true;
		for (auto it = checker.begin(); it != checker.end(); it++)
		{
			if (std::future_status::ready != it->wait_for(std::chrono::milliseconds(10)))
			{
				all_check_thread_finished = false;
				break;
			}
			
		}

		if (all_check_thread_finished)
		{
			break;
		}

		qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
	}
	bool record_start = false;

	for (auto it = checker.begin(); it != checker.end(); it++)
	{
		int ret = it->get();
		ControlApiLogger(ret, EagleLog_C_Start_Selfcheck);
		if (!record_start)
		{
			if (ret == 0)
			{
				record_start = true;
			}
		}
	}
	qApp->restoreOverrideCursor();

	if (record_start)
	{
		return QDialog::done(QEvent::User + 0);
	}
	else
	{
		return QDialog::done(QEvent::User + 1);
	}
}

checkRecordDlg::checkRecordDlg(QWidget* parent)
:QDialog(parent), ui(new Ui::checkSet)
{
	ui->setupUi(this);
	setFixedSize(380, 105);
}

int checkRecordDlg::getSelCheckType()
{
	return ui->comboBox->currentIndex();
}

//////////////////////////////////////////////////////////////////////////
//  [12/8/2016 ejitec]
snapDlg::snapDlg(QWidget* parent, QString &decoder_name, QPoint& start, QPoint& end, int w, int h, int nDepth, uchar* buf)
:QDialog(parent)
, ui(new Ui::snapShotDlg)
{
	ui->setupUi(this);

	connect(ui->btn_path, &QPushButton::clicked, this, [this]()
	{
		QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
			"/home",
			QFileDialog::ShowDirsOnly
			| QFileDialog::DontResolveSymlinks);

		ui->lineEdit_Path->setText(dir);
	});

	_RIO = new RIOManager(start, end, w, h, nDepth, buf);
	int sw = _RIO->GetRIOCols();
	sw += 3;
	sw = (sw / 4 - 1) * 4; 
	/************************************************************************/
	/* 
		Constructs an image with the given width, height and format, that uses an existing memory buffer, data. 
		The width and height must be specified in pixels, 
		data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned.
	*/
	/************************************************************************/
	int dest_len = sw * _RIO->GetRIORows() * 3;
	unsigned char *dest = new unsigned char[dest_len];
	img_buf = new unsigned char[dest_len];
	source = new unsigned char[sw * _RIO->GetRIORows() * ((_RIO->GetRIOBitWidth() + 7) / 8)];
	int sh = _RIO->GetRIORows();

	for (int i = 0; i < sh; i++)
	{
		for (int j = 0; j < sw; j++)
		{
			if (_RIO->GetRIOBitWidth() > 8)
			{
				((unsigned short*)source)[i * sw + j] = _RIO->GetRIOValue(j, i);
			}
			else
			{
				source[i * sw + j] = _RIO->GetRIOValue(j, i);  // x  y
			}
		}
	}

	DecodeRequestStruct request;
	request.needResize = false;
	request.muitiplier = 4;
	request.IsRgbSort = false;
	request.LeftRightReverse = false;
	request.UpDownReverse = false;
	request.data_source_is_resized = false;
	DecoderPluginMgr::getInstance()->getDecoder(decoder_name.toStdWString())->Decode(
		dest,
		dest_len,
		source,
		_RIO->GetRIOBitWidth(),
		/*_RIO->GetRIOCols()*/sw,
		_RIO->GetRIORows(),
		&request
		);
	DecoderPlugin::DecodedParam decoded_param(_RIO->GetRIOBitWidth(), /*_RIO->GetRIOCols()*/sw, _RIO->GetRIORows());
	DecoderPluginMgr::getInstance()->getDecoder(decoder_name.toStdWString())->GetDecodedParam(
		decoded_param,
		decoded_color_depth,
		decoded_column,
		decoded_line,
		&request
		);

	int pixels = decoded_column * decoded_line;
	for (int i = 0; i < pixels; i++){
		img_buf[i * 3] = dest[(pixels - i) * 3 - 1];
		img_buf[i * 3 + 1] = dest[(pixels - i) * 3 - 2];
		img_buf[i * 3 + 2] = dest[(pixels - i) * 3 - 3];
	}

	//	_Image = new QImage(img_buf, decoded_column, decoded_line, QImage::Format_RGB888);
 	_Image = new QImage(decoded_column, decoded_line, QImage::Format_RGB888);
	qDebug() << "ImageLen:" << _Image->byteCount() << " SrcLen:" << dest_len << " W,H:" << _Image->width() << " " << _Image->height();

 	memcpy(_Image->bits(), img_buf, qMin(_Image->byteCount(),dest_len));
	
	delete[] dest;
}

void snapDlg::accept()
{
	qDebug() << "snapDlg::accept()";

	if (ui->lineEdit_Path->text() == "")
	{
		QMessageBox::warning(this, GetMessageBoxTitle(), GetLogFormat(EagleLog_M_Select_Non_Export_Dir));
		return;
	}

	QString name = ui->lineEdit_nam->text();
	if (name.isEmpty())
		name = "EagleSnapshot";

	QString strPath = ui->lineEdit_Path->text() + "/" + name;
	
	if (ui->cmb_type->currentText() == "raw")
	{
		int buf_size = _RIO->GetRIORows() * _RIO->GetRIOCols() * ((_RIO->GetRIOBitWidth() + 7) / 8);
		std::ofstream ofs_data;
		ofs_data.open(strPath.toStdString().c_str(), std::ofstream::out | std::ofstream::binary);
		if (ofs_data.is_open() && ofs_data.good())
		{
			ofs_data.write((char*)source, buf_size);
			ofs_data.close();
			std::string config_name = name.toStdString() + std::string(".conf");
			QFile file(strPath + ".conf");
			file.open(QFile::Append);
			QTextStream data(&file);
			data << QString("columns = %1\n").arg(_RIO->GetRIOCols());
			data << QString("lines = %1\n").arg(_RIO->GetRIORows());
			data << QString("bits = %1\r\n").arg(_RIO->GetRIOBitWidth());
			data.flush();
			file.close();
		}
	}
	else
	{
		QString filePath = QString("%1.%2").arg(strPath, ui->cmb_type->currentText());
		_Image->save(filePath, ui->cmb_type->currentText().toStdString().c_str());
	}

	QDialog::accept();
}

snapDlg::~snapDlg()
{
	delete[] source;
	delete[] img_buf;
	delete _Image;
	delete _RIO;
}

//  [12/9/2016 ejitec]


// mode [12/9/2016 ejitec]
class tableMode : public QAbstractTableModel
{
	//Q_OBJECT
public:
	tableMode(QObject *parent, RIOManager* RIO)
		:QAbstractTableModel(parent)
		, _RIO(RIO)

	{
		_left = _RIO->GetSubRIO().left();
		_top = _RIO->GetSubRIO().top();
		
	}

	int rowCount(const QModelIndex &parent = QModelIndex()) const
	{
		//qDebug() << "rowCount:" << _RIO->GetRIORows();
		return _RIO->GetRIORows();
	}
	int columnCount(const QModelIndex &parent = QModelIndex()) const
	{
		//qDebug() << "columnCount:" << _RIO->GetRIOCols();
		return _RIO->GetRIOCols();
	}

	QVariant headerData(int section, Qt::Orientation orientation, int role) const
	{
		switch (role)
		{
		case Qt::DisplayRole:
		{
			if (orientation == Qt::Horizontal)
			{
				return QString::number(section + _left);
			}
			else if (orientation == Qt::Vertical)
			{
				return QString::number(section + _top);
			}

			break;
		}
		case Qt::TextAlignmentRole:
		{
			return Qt::AlignCenter;
			break;
		}
		case Qt::FontRole:
		{
			QFont boldFont;
			boldFont.setBold(true);
			return boldFont;
			break;
		}
		case Qt::ForegroundRole:
		{
			QBrush ForeG(Qt::darkBlue);
			return ForeG;
			break;
		}
		default:
			break;
		}

		return QVariant();
	}

	QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
	{
		switch (role)
		{
		case Qt::DisplayRole:
		{
			qDebug() << index.row() << " " << index.column();
			int value = _RIO->GetRIOValue(index.column(),index.row());
			return QString("0x%1").arg(value, 4, 16, QChar('0'));
			break;
		}
		case Qt::TextAlignmentRole:
		{
			return Qt::AlignCenter;
			break;

		}
		default:
			
			break;
		}

		return QVariant();
	}

	//bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole);
private:

	RIOManager* _RIO;
	int _left;
	int _top;
};

//#include "tipDlgs.moc"

hexViewDlg::hexViewDlg(QWidget* parent, QPoint& start, QPoint& end, int w, int h, int nDepth, uchar* buf)
:QDialog(parent)
, ui(new Ui::hexView)
, _RIO(nullptr)
{
	ui->setupUi(this);
	_RIO = new RIOManager(start, end, w, h, nDepth, buf);

	if (_RIO)
	{
		_tableMode = new tableMode(this, _RIO);
		ui->tableHex->setModel(_tableMode);
	}

//	ui->tableHex->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
// 	ui->tableHex->resizeColumnsToContents();
}

hexViewDlg::~hexViewDlg()
{
	delete _RIO;
}


// 系统信息对话框
systemInfoDlg::systemInfoDlg(QWidget* parent, std::vector<int>& device_list)
:QDialog(parent), ui(new Ui::softInfoDlg)
{
	ui->setupUi(this);
	QPalette pe;
	pe.setColor(QPalette::WindowText, Qt::black);
	QFont font("Consolas", 11, QFont::Medium);

	int major = 0, minor = 0;
	EagleData_GetVersion(&major, &minor);
	const QString buildTm = GetCompileDateTime();
	QString soft = tr("软件版本：%1\n编译日期: %2\nSDK版本：%3.%4")
		.arg(QString::fromWCharArray(EAGLE_VERSION), buildTm).arg(major).arg(minor);
	ui->softinfo->setWordWrap(true);
	ui->softinfo->setPalette(pe);
	ui->softinfo->setFont(font);
	ui->softinfo->setText(soft);

	QGridLayout* gLay = new QGridLayout(ui->scrollHardWare);
	//ui->scrollHardWare->setBackgroundRole(QPalette::Light);
	ui->scrollArea->setFrameShape(QFrame::NoFrame);
	gLay->setMargin(0);
	for (auto it = device_list.cbegin(); it != device_list.end(); it++)
	{
		QLabel* tmpLabel = new QLabel(this);
		tmpLabel->setWordWrap(true);
		tmpLabel->setPalette(pe);
		tmpLabel->setFont(font);
		char fpga_serial[32] = { '\0' };
		char dev_serial[32] = { '\0' };
		wchar_t dev_name[32] = { '\0' };
		char firmware_version[32] = { '\0' };

		EagleControl_GetFpgaSerial(*it, fpga_serial);
		EagleControl_GetDeviceSerial(*it, dev_serial);
		EagleControl_GetDeviceName(*it, dev_name);
		EagleControl_GetElfVersion(*it, firmware_version);

		QString strText = tr("设备名称：%1\n固件版本：%2\nFPGA版本：%3\n设备序列号：%4\n")
			.arg(QString::fromWCharArray(dev_name), firmware_version, fpga_serial, dev_serial);

		tmpLabel->setText(strText);

		gLay->addWidget(tmpLabel, gLay->rowCount(), 0, Qt::AlignTop);
	}
}


// 西光所 附加参数 [6/1/2017 xystar]
extraParamsDlg::extraParamsDlg(QWidget* parent)
:QDialog(parent), ui(new Ui::extraParamsDlg), _caller(qobject_cast<QDisPlayWidget*>(parent))
{
	ui->setupUi(this);

	ui->cmb_angle->clear();
	ui->cmb_angle->setEditable(false);
	ui->cmb_angle->addItems(QString("0,1,2,3,4,5,6,7,8,9").split(","));

	ui->cmb_frmOffset->clear();
	ui->cmb_frmOffset->setEditable(false);
	for (int i = -10; i <= 10; i++)  // 0 -- 21
	{
		ui->cmb_frmOffset->addItem(QString::number(i));
	}

	XGSExpParams* _params = _caller->getXGSExpParms();
	ui->lineEdit_tm->setText(QString::number(std::get<0>(*_params)));
	ui->cmb_angle->setCurrentText(QString::number(std::get<1>(*_params)));
	ui->cmb_frmOffset->setCurrentText(QString::number(std::get<2>(*_params)));
}

void extraParamsDlg::accept()
{
	XGSExpParams* _params = _caller->getXGSExpParms();

	std::get<0>(*_params) = ui->lineEdit_tm->text().toInt();
	std::get<1>(*_params) = ui->cmb_angle->currentText().toInt();
	std::get<2>(*_params) = ui->cmb_frmOffset->currentText().toInt();

	QString strText = QString("%1|%2|%3").arg(ui->lineEdit_tm->text()
		, ui->cmb_angle->currentText(), ui->cmb_frmOffset->currentText());

	EagleConfigFile::getInstance()->SetDeviceCameraExtraParam(_caller->DevID(),_caller->CCDID() , strText);

	QDialog::accept();
}


// 十字丝设置 [12/5/2017 xystar]
crossWireSetDlg::crossWireSetDlg(QWidget* parent)
:QDialog(parent), ui(new Ui::crossWireDlg)
{
	ui->setupUi(this);
	ui->cmbColor->setCurrentIndex(EagleConfigFile::getInstance()->m_nColor);
	ui->cmbSize->setCurrentText(EagleConfigFile::getInstance()->m_szSize);
	if (-1 == ui->cmbSize->findText(EagleConfigFile::getInstance()->m_szSize))
	{
		ui->cmbSize->addItem(EagleConfigFile::getInstance()->m_szSize);
	}
	ui->check_show->setChecked(EagleConfigFile::getInstance()->m_nShow);

	QIntValidator val;
	val.setRange(1, 100);
	ui->lineEditWidth->setValidator(&val);
	ui->lineEditWidth->setText(QString::number(EagleConfigFile::getInstance()->m_nLineWidth));
	connect(ui->btn_ok, &QPushButton::clicked, this, [this](){
		this->accept();
	});

	connect(ui->btn_apply, &QPushButton::clicked, this, &crossWireSetDlg::on_Apply);
}

void crossWireSetDlg::on_Apply()
{
	EagleConfigFile::getInstance()->m_nColor = ui->cmbColor->currentIndex();
	EagleConfigFile::getInstance()->m_nShow = ui->check_show->isChecked() ? 1 : 0;
	EagleConfigFile::getInstance()->m_nLineWidth = ui->lineEditWidth->text().toInt();

	QString strText = ui->cmbSize->currentText().toLower();
	QStringList strSize = strText.split("*");
	EagleConfigFile::getInstance()->m_tCrossSize = QSize(40, 40);
	
	if (strSize.size() == 2)
	{
		EagleConfigFile::getInstance()->m_tCrossSize = QSize(strSize[0].toInt(), strSize[1].toInt());
	}

	EagleConfigFile::getInstance()->m_szSize = strText;
}

void crossWireSetDlg::accept()
{
	on_Apply();

	EagleConfigFile::getInstance()->saveCroseWire();

	QDialog::accept();
}


#ifdef SIMULATE_HAS_IMPLEMENTED
// 仿真 [11/24/2017 xystar]
#include "../include/user_define/CLSimulation.h"
#include <sstream>

CEvfsCfgDlg::CEvfsCfgDlg(int devID,QWidget* parent)
:QDialog(parent), ui(new Ui::evfsCfgDlg), _device_id(devID)
{
	QFrame* lines[2] = { 0 };

	for (auto& it: lines)  // 强制引用自身
	{
		it = new QFrame(this);
		it->setFrameShape(QFrame::HLine);
		it->setFrameShadow(QFrame::Sunken);
	}

	ui->setupUi(this);
	ui->checkBox_type->setChecked(true);
	ui->formLayoutTop->setWidget(ui->formLayoutTop->rowCount(), QFormLayout::SpanningRole, lines[0]);
	ui->formLayoutDown->setWidget(ui->formLayoutDown->rowCount(), QFormLayout::SpanningRole, lines[1]);
	export_status_timer = new QTimer();
	connect(export_status_timer, &QTimer::timeout, this, &CEvfsCfgDlg::on_timeOut);
	connect(ui->btn_sel, &QPushButton::clicked, this, [this](){
		QString path = QFileDialog::getExistingDirectory(this, "Pls select exist path", "d:/");
		ui->lineEdit_path->setText(path);
	});

	bool Operate_Result = false;
	unsigned short major = 0, minor = 0;
	int ret;
	wstring	information;
	_wsystem(L"net start EagleVFS");
	QThread::sleep(1);

	do {
		// connect
		ret = EagleDataVfs_Connect();
		if (ret != 0)
		{
			information = wstring(L"Connect Failed, May not install driver");
			break;
		}

		// bind to system root volume
		wchar_t system_path[MAX_PATH];
		GetSystemDirectory(system_path, MAX_PATH);
		_wcsupr_s(system_path, MAX_PATH);

		ret = EagleDataVfs_Bind(system_path[0]);
		if (ret != S_OK)
		{
			information = GetLogFormatString(ret, EagleLog_C_Evfs_Bind).toStdWString();
			break;
		}
		Operate_Result = true;

		// subst directory to an unused volume letter
		wchar_t used_volume = GetFirstUnusedVolumeLetter();
		wchar_t system_volume = system_path[0];
		{
			wstringstream stream;
			stream << L"Record File In " << system_volume << L":\\RECORD_DATA";
			information = stream.str();
			break;
		}

		wstringstream stream;
		stream << L"subst " << used_volume << L": " << system_volume << L":\\RECORD_DATA";
		_wsystem(stream.str().c_str());
		stream.str(L"");
		setBindVolumeLetter(used_volume);
		stream << L"Record File In " << used_volume;
		information = stream.str();

	} while (0);

	ui->lineEdit_recPath->setText(QString::fromStdWString(information));
	if (Operate_Result)
	{
		ui->btn_write->setEnabled(true);
	}

	ui->cmb_colum->addItems(EagleConfigFile::getInstance()->support_column);
	ui->cmb_line->addItems(EagleConfigFile::getInstance()->support_line);
	ui->cmb_colum->setCurrentIndex(0);
	ui->cmb_line->setCurrentIndex(0);
	//	buttonOpenExport->Enable(false);
	ui->btn_cancel->setEnabled(false);
	ui->probar->setRange(0, 100);
	ui->probar->setValue(0);
}

wchar_t CEvfsCfgDlg::GetFirstUnusedVolumeLetter()
{
	DWORD	logicalDrive = 0;
	int		i;
	wchar_t	letter = 'A';

	logicalDrive = GetLogicalDrives();

	if (logicalDrive == 0)
		return 0;

	for (i = 0; i < 26; i++)
	{
		if (logicalDrive & (1 > i))
			continue;
		return letter + i;
	}

	return 0;
}

void CEvfsCfgDlg::accept()
{
	QDialog::accept();
}

QString CEvfsCfgDlg::GetLogFormatString(int ret, int type)
{
	QString pre = GetLogFormat((EagleLogIndexType)type);

	return QString("%1:%2").arg(pre).arg(ret);
}

void CEvfsCfgDlg::on_timeOut()
{
	eagle_write_status status;
	int ret = EagleDataVfs_GetWriteStatus(_device_id, &status);
	if (status.write_status != 1)
	{
		export_status_timer->stop();
		ui->btn_write->setEnabled(true);
		ui->btn_cancel->setEnabled(false);
	}

	QString write_status_label = GetLogFormat(EagleLog_C_Evfs_Write_Status);
	if (status.write_status == 1 || status.write_percent == 1)
		write_status_label += QString("").sprintf(" %f%%", status.write_percent * 100);
	else
		write_status_label += QString("").sprintf(" %08X", status.write_result);
	ui->lineEdit_info->setText(write_status_label);
	ui->probar->setValue(status.write_percent * 100);
}

void CEvfsCfgDlg::on_cancelWrite()
{
	int ret = EagleDataVfs_CancelWrite(_device_id);

	ui->btn_cancel->setEnabled(false);
	export_status_timer->stop();
	ui->btn_write->setEnabled(true);
	ui->lineEdit_info->setText(GetLogFormatString(ret, EagleLog_C_Evfs_Stop_Write));
}

void CEvfsCfgDlg::setInfo(QString text)
{
	ui->lineEdit_recPath->setText(text);
}

void CEvfsCfgDlg::on_startWrite()
{
	QString source_file = ui->lineEdit_path->text();
	if (source_file.isEmpty())
	{
		return;
	}

	unsigned long value;
	QString task_name = ui->lineEdit_taskNam->text();
	QRegExp reg("^[a-zA-Z0-9_]{1,32}$");
	if (!reg.exactMatch(task_name))
	{
		wxMessageBox(GetLogFormat(EagleLog_M_Invalid_Task_Name_Alarm), GetMessageBoxTitle());
		return;
	}

	if (ui->checkBox_type->isChecked())
	{
		ealge_vfs_write_stream write_stream;
		memset(&write_stream, 0x00, sizeof(write_stream));
		source_file.toWCharArray(write_stream.SourceFile);
		//wmemcpy_s(write_stream.SourceFile, MAX_EVFS_NAME_LEN,,source_file.size);
		//wmemcpy_s(write_stream.TaskName, sizeof(write_stream.TaskName) / sizeof(wchar_t), task_name.wc_str(), task_name.Length());
		task_name.toWCharArray(write_stream.TaskName);
		value =  ui->lineEdit_colorDepth->text().toLong();

		if (value != 8 && value != 10 && value != 12 && value != 14 && value != 16)
		{
			wxMessageBox(tr("请输入合法色深[8,10,12,14,16]"), GetMessageBoxTitle());
			return;
		}

		write_stream.ColorDepth = (unsigned short)value;
		write_stream.Column = (unsigned short)ui->cmb_colum->currentText().toLong();
		write_stream.Line = (unsigned short)ui->cmb_colum->currentText().toLong();

		int ret = EagleDataVfs_OpenWriteStream(_device_id, &write_stream);
		ui->lineEdit_info->setText(GetLogFormatString(ret, EagleLog_C_Evfs_Start_Write));
		if (ret == 0)
		{
			export_status_timer->start(1000);
			ui->btn_write->setEnabled(false);
			ui->btn_cancel->setEnabled(true);
			ui->probar->setValue(0);
		}
	}
	else
	{
		ealge_vfs_write_files write_stream;
		memset(&write_stream, 0x00, sizeof(write_stream));
		int offset = source_file.indexOf('\\');

		//wmemcpy_s(write_stream.SourceDir, MAX_EVFS_NAME_LEN, qPrintable(source_file), offset);
		source_file.left(offset).toWCharArray(write_stream.FileExtName);
		offset = source_file.lastIndexOf('.');
		if (offset == 0)
		{
			wxMessageBox(tr("文件没有后缀名"), GetMessageBoxTitle());
			return;
		}
// 		wmemcpy_s(write_stream.FileExtName, MAX_EVFS_NAME_LEN, source_file.wc_str() + offset + 1, source_file.length() - offset - 1);
// 		wmemcpy_s(write_stream.TaskName, sizeof(write_stream.TaskName) / sizeof(wchar_t), task_name.wc_str(), task_name.Length());
		source_file.mid(offset + 1).toWCharArray(write_stream.FileExtName);
		task_name.toWCharArray(write_stream.TaskName);
		value = ui->lineEdit_colorDepth->text().toLong();

		if (value != 8 && value != 10 && value != 12 && value != 14 && value != 16)
		{
			wxMessageBox(tr("请输入合法色深[8,10,12,14,16]"), GetMessageBoxTitle());
			return;
		}
		write_stream.ColorDepth = (unsigned short)value;
		write_stream.Column = (unsigned short)ui->cmb_colum->currentText().toLong();
		write_stream.Line = (unsigned short)ui->cmb_colum->currentText().toLong();


		int ret = EagleDataVfs_OpenWriteRawFiles(_device_id, &write_stream);
		ui->lineEdit_info->setText(GetLogFormatString(ret, EagleLog_C_Evfs_Start_Write));
		if (ret == 0)
		{
			export_status_timer->start(1000);
			ui->btn_write->setEnabled(false);
			ui->btn_cancel->setEnabled(true);
			ui->probar->setValue(0);
		}
	}
}

#endif